/**
 * 用户相关服务
 */
import request from '@/utils/request'
import {getToken, setToken} from "./auth";

/**
 * Promise封装uni.checkSession
 */
export function checkSession() {
    return new Promise(function (resolve, reject) {
        uni.checkSession({
            success: function () {
                resolve(true);
            },
            fail: function () {
                reject(false);
            }
        })
    });
}

// 获取个人信息
export const getUserInfoByWx = () => {
    return new Promise((resolve, reject) => {
        uni.getUserProfile({
            desc: '获取你的昵称、头像',
            success: function (data) {
                console.log(data, '用户信息')
                resolve(data)
            },
            fail: function (error) {
                console.log(error, '用户信息')
                reject(error)
            }
        });
    })
}

/**
 * 调用微信登录
 */
export function loginByWeixin(info) {
    return new Promise(function (resolve, reject) {
        return login().then((res) => {
            // 登录远程服务器
            request({
                url: "/wx/auth/login_by_weixin",
                headers: {
                    isToken: false
                },
                method: 'post',
                timeout: 20000,
                'data': {code: res.code, userInfo: info.userInfo}
            }).then(res => {
                if (res.code === 200) {
                    uni.setStorageSync('sessionKey', res.data.sessionKey);
                    uni.setStorageSync('openId', res.data.openId);
                    uni.setStorageSync('userInfo', res.data.userInfo);
                    setToken(res.data.token);

                    resolve(res);
                } else {
                    reject(res);
                }
            }).catch((err) => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        })
    });
}

/**
 * Promise封装uni.login
 */
export function login() {
    return new Promise(function (resolve, reject) {
        uni.login({
            provider: 'weixin',
            onlyAuthorize: true,
            success: res => {
                console.log(res, '获取信息')
                if (res.code) {
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            fail: err => {
                reject(err);
            }
        });
    });
}

/**
 * 判断用户是否登录
 */
export function checkLogin() {
    return new Promise(function (resolve, reject) {
        if (uni.getStorageSync('userInfo') && getToken()) {
            checkSession().then(() => {
                resolve(true);
            }).catch(() => {
                reject(false);
            });
        } else {
            reject(false);
        }
    });
}